package org.middleware.controller.system;

import lombok.extern.slf4j.Slf4j;
import org.middleware.common.AuthenticationToken.RequireLogin;
import org.middleware.common.BusinessException;
import org.middleware.controller.common.CommonHttpResponse;
import org.middleware.entity.system.SysPermissions;
import org.middleware.service.system.SysPermissionsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequireLogin
@Slf4j
public class SysPermissionsController {

    @Autowired
    private SysPermissionsService permissionsService;

    @PostMapping("/permissions")
    public CommonHttpResponse insert(@RequestBody SysPermissions permission) {
        try {
            permissionsService.insert(permission);
            return CommonHttpResponse.success("新增成功");
        } catch (BusinessException e) {
            return CommonHttpResponse.fail(400, e.getMessage());
        } catch (Exception e) {
            log.error("权限新增异常：", e);
            return CommonHttpResponse.fail(500, "权限新增异常");
        }
    }

    @GetMapping("/permissions/systems/{id}")
    public CommonHttpResponse searchBySystem(@PathVariable int id) {
        try {
            List<SysPermissions> result = permissionsService.searchPermissionsBySystem(id);
            return CommonHttpResponse.success(result);
        } catch (BusinessException e) {
            return CommonHttpResponse.fail(400, e.getMessage());
        } catch (Exception e) {
            log.error("权限查询异常：", e);
            return CommonHttpResponse.fail(500, "权限查询异常");
        }
    }

    @PutMapping("/permissions")
    public CommonHttpResponse update(@RequestBody SysPermissions permission) {
        try {
            permissionsService.update(permission);
            return CommonHttpResponse.success("修改成功");
        } catch (BusinessException e) {
            return CommonHttpResponse.fail(400, e.getMessage());
        } catch (Exception e) {
            log.error("权限修改异常：", e);
            return CommonHttpResponse.fail(500, "权限修改异常");
        }
    }

    @DeleteMapping("/permissions/{id}")
    public CommonHttpResponse delete(@PathVariable int id) {
        try {
            permissionsService.delete(id);
            return CommonHttpResponse.success("删除成功");
        } catch (BusinessException e) {
            return CommonHttpResponse.fail(400, e.getMessage());
        } catch (Exception e) {
            log.error("权限删除异常：", e);
            return CommonHttpResponse.fail(500, "权限删除异常");
        }
    }
}
